/**
 * @author zhangqiang
 * @date   17/7/18
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Toast, Popup, Switch} from 'antd-mobile'
import {
	InputItem,
	FooterAlertMask,
} from '../../components/home'
//通用组件
import BottomMenu from '../../../../../../../src/js/components/bottomMenu';
import {
	getDefaultAddress,
	submitFormData
} from  '../../actions/homeActions'
import {
	getAddAddress,
} from '../../actions/addAddressActions';
import '../../../styles/home.scss';
import common from '../../utils/common'
import style from './index.scss'

class Home extends Component {
	constructor(props) {
	super(props);
	this.state = {
		sendTypeName: '普通快递', //寄送类型
		sendType: 1,
		isShowSendTypeList: false, 
		sendTypeData: [   //取证方式
			{times: 1, timesName: "普通快递"},
			{times: 2, timesName: "香港快递"}
		],
		goodsTypeName: '文件',
		goodsType: '01',
		isShowGoodsTypeList: false, 
		goodsData: [
			{times: '01', timesName: "文件"},
			{times: '02', timesName: "数码产品"},
			{times: '03', timesName: "生活用品"},
			{times: '04', timesName: "校园包裹"},
			{times: '05', timesName: "其他物品"}
		],
		isAgree: false,  //协议
	};
	}
	
	componentWillMount(){
		this.setState(
			Object.assign({},JSON.parse(sessionStorage.getItem('cacheAllState')))
		)
	}

	componentDidMount() {
		common.setViewTitle('EMS寄快递');
		this.props.dispatch(getDefaultAddress({}))
	}

	componentWillUnmount() {
		//离开页面存储全局状态
		sessionStorage.setItem('cacheAllState',JSON.stringify(this.state))
	}

	componentDidUpdate() {
		/*
		* 兼容ios点击输入框遮挡tag
		* */
		let inputAll = document.getElementsByTagName('input');
		for(let i=0;i<inputAll.length;i++){
			if(inputAll[i].type != 'checkbox'){ //复选框不用设置样式
				inputAll[i].onfocus = () => {
					document.querySelector('.footNavPoise').style.position='static'
				}
				inputAll[i].onblur = () => {
					document.querySelector('.footNavPoise').style.position='fixed'
				}
			}
		}
	}

	toUrl(url) {
		this.context.router.push(url);
	}

	/*	寄递类型
	 *   times 类型
	 *   timesName 字段
	 * */
	showSendTypeMask(){
		let props = {
			data: this.state.sendTypeData,
			timesIndex: this.state.sendType,   //默认选项
			onChoose: (times,timesName) => {
				console.log(times)
				this.setState({
					sendType: times,
					sendTypeName: timesName
				})
				Popup.hide(); //隐藏
			}
		};
		const y = scrollY
		Popup.show(<FooterAlertMask {...props}/>, {animationType: 'slide-up'});
		scrollTo(undefined, y)
	}

	/*	寄托物品
	 *   times 类型
	 *   timesName 字段
	 * */
	showGoodsTypeMask(){
		let props = {
			data: this.state.goodsData,
			timesIndex: this.state.goodsType,   //默认选项
			onChoose: (times,timesName) => {
				this.setState({
					goodsType: times,
					goodsTypeName: timesName
				})
				Popup.hide(); //隐藏
			}
		};
		const y = scrollY
		Popup.show(<FooterAlertMask {...props}/>, {animationType: 'slide-up'});
		scrollTo(undefined, y)
	}

	/*
	*   是否同意协议
	* */
	isAgreeState(){
		this.setState({
			isAgree: !this.state.isAgree
		});
	}

	//底部跳转
	bottomHandle(index) {
		console.log('home',index)
		if (index == 0) {
			this.props.router.push('/');
		} else if (index == 1) {
			this.props.router.push('checkExpress');
		} else {
			this.props.router.push('orderList');
		}
	}

	submit(){
		let { sendType, goodsType, sendTypeName, goodsTypeName, isAgree } = this.state,
			address = JSON.parse(localStorage.getItem('choiceAddress'));

			if(!address){
				Toast.info('请填写完整的地址信息',1);
				return;
			}else if(!isAgree){
				let hint = sendType == 1?'请阅读并同意《国内特快专递承诺服务免责条款》':'请阅读并同意《香港快递承诺条款》'
				Toast.info(hint,1);
				return;
			}

		let postData = {
			"payType": 0,//到付
			"mailingAddressRange": sendType,
			"postUserName": address.contactName,
			"goodType": goodsType,
			'address.contactName': address.contactName,
            'address.cellNum': address.cellNum,
            'address.provinceId': address.provinceId,
            'address.cityId': address.cityId,
            'address.countyId': address.countyId,
            'address.provinceName': address.provinceName,
            'address.cityName': address.cityName,
            'address.countyName': address.contactName,
            'address.street': address.street,
            'address.fullAddr': address.fullAddr.replace(null,'')
		};
		this.props.dispatch(submitFormData(postData,(resultData)=>{
			let orderId = resultData.orderIds[0].id,
				chargeOrderId = resultData.chargeOrderId;
				postData['orderId'] = orderId
				postData['chargeOrderId'] = chargeOrderId
				postData['sendTypeName'] = sendTypeName
				postData['goodsTypeName'] = goodsTypeName 
				postData['timeDiffer'] = resultData.timeDiffer
				sessionStorage.setItem('cacheOrderPay', JSON.stringify(postData));

				this.toUrl(`payment/${resultData.payOrderId}/${chargeOrderId}`)
		}))
	}

	render() {
		let cacheAddress,
			visaType = this.state.visaType;
		if(!this.props.isShowChice||sessionStorage.getItem('isShowChice')){
			cacheAddress = JSON.parse(localStorage.getItem('choiceAddress'))
		}else {
			cacheAddress = this.props.defaultAddress&&this.props.isShowChice? this.props.defaultAddress:
			JSON.parse(localStorage.getItem('choiceAddress'))?JSON.parse(localStorage.getItem('choiceAddress')):'';  //进入地址列表缓存的地址信息  选择地址的缓存

			localStorage.setItem('choiceAddress',JSON.stringify(cacheAddress))
		}
		let { sendType, sendTypeName, goodsTypeName, isAgree } = this.state;
		return (
			
			<div className={style.home}>
				<div className={style.sendContainer}>
					<div className={style.topLine}></div>
					<div className={style.content}>
						{/* 顶部logo-- start */}
						<div className={style.trademark}>
							<img className={style.logo} src="./images/EMSlogo-1@2x.png" alt=""/>
							<div className={style.phone}>
								<div>标准快递</div>
								<div>客服电话：020-11183</div>
							</div>
						</div>
						{/* 顶部logo-- end */}
						{/* 地址-- start */}
						<div className={style.address}>
							<div className={style.title}>上门揽件信息</div>
							<div className={style.choiceContainer}>
							{
								cacheAddress&&cacheAddress.fullAddr!=''?
								<div  onClick={e => this.toUrl('addressList')}>
									<div>
										<span className={style.name}>{cacheAddress.contactName}</span>
										<span>{cacheAddress.cellNum}</span>
										<img className={style.jump} src="./images/icon_to_r.png" alt=""/>
									</div>
									<div>{cacheAddress.fullAddr}</div>
								</div>
								:
								<div className={style.noAddress} onClick={e => this.toUrl('addressList')}>
									请选择上门揽件详细地址
									<img src="./images/icon_to_r.png" alt=""/>
								</div>
							}
							</div>
						</div>
						{/* 地址-- end */}
						<div style={{height: '.1rem'}}></div>
						{/* 寄递类型 寄拖物品-- start */}
						<div className={style.sendTypeBox}>
							<div className={style.sendType}>
								<div className={style.title}>寄递类型</div>
								<div className={style.sendTypeSelect} onClick={e => this.showSendTypeMask()}>
									{sendTypeName}
									<img src="./images/icon_to_r.png" alt=""/>
								</div>
							</div>
							<div className={style.sendType}>
								<div className={style.title}>寄托物品</div>
								<div className={style.sendTypeSelect} onClick={e => this.showGoodsTypeMask()}>
									{goodsTypeName}
									<img src="./images/icon_to_r.png" alt=""/>
								</div>
							</div>
						</div>
						{/* 寄递类型 寄拖物品-- end */}
						{/* 免责条款-- start */}
						<div className={style.agreeBox}>
							<span className={style.agreeEnlarge} onClick={()=>{this.isAgreeState()}}>
								<img className={style.agree} src={isAgree?'./images/agree.png':'./images/noCheck.png'} alt=""/>
								<span className={style.determine}>我同意</span>
							</span>
							<span className={style.agreeBtn} onClick={()=>{this.toUrl(`agreement/${sendType}`)}}>
								{
									sendType == 1?'《国内特快专递承诺服务免责条款》':'《香港快递承诺条款》'
								}
							</span>
						</div>
						{/* 免责条款-- start */}
						<div className={style.btnBox}>
							<button className={style.handle} type='button' onClick={()=>{this.submit()}}>呼叫快递员上门</button>
						</div>
					</div>
				</div>

				<div className={style.explain}>最终资费以快递员实际计价为准</div>

				{/*底部导航菜单 start checkEms_checked*/}
				<BottomMenu active={0} onChange={(index) => {
					this.bottomHandle(index);
				}} data={[{
					text: '寄快递',
					img: './images/sendEms.png',
					checkedImg: './images/sendEms_checked.png'
				},{
					text: '查快递',
					img: './images/checkEms.png',
					checkedImg: './images/checkEms_checked.png'
				},{text: '我的订单', img: './images/my.png', checkedImg: './images/my_checked.png'}]}/>
				{/*底部导航菜单end*/}
			</div>
		)
	}
}

//使用context
Home.contextTypes = {
    router: React.PropTypes.object.isRequired
};

Home.defaultProps = {
	defaultAddress: {
		fullAddr:'',
		street:''
	}
};

function mapStateToProps(state) {
	return Object.assign({}, state.homeReducer, state.addressList);
}

export default connect(mapStateToProps)(Home);

